<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="入库单号" prop="storageNumber">
        <el-input
          v-model="queryParams.storageNumber"
          placeholder="请输入入库单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓库" prop="ordersId">
        <treeselect
          v-model="queryParams.ordersId"
          :options="warehouseOptions"
          :show-count="true"
          placeholder="请输入仓库"
          style="width: 210px"
        />
      </el-form-item>
      <el-form-item label="采购单号" prop="ordersNumber">
        <el-input
          v-model="queryParams.ordersNumber"
          placeholder="请输入采购单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['depot:ProcuredStorage:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['depot:ProcuredStorage:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['depot:ProcuredStorage:remove']">删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['depot:ProcuredStorage:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="ProcuredStorageList"
      @selection-change="handleSelectionChange"
      style="width: 100%"
    >
      <!-- 这里是展开列 -->
      <el-table-column type="expand">
        <template slot-scope="scope">
          <!-- 这里是展开的详细内容，可以是子表格或者更详细的单条数据展示 -->
          <el-table
            :data="scope.row.procuredStorageDetails"
            style="width: 100%"
          >
            <!-- 图片列 -->
            <el-table-column label="图片" prop="imgName" align="center">
              <template slot-scope="scope">
                <div class="image-container">
                  <!-- 判断是否有图片 -->
                  <template
                    v-if="
                      scope.row.productImages &&
                      scope.row.productImages.length > 0
                    "
                  >
                    <image-preview
                      v-for="(image, index) in scope.row.productImages"
                      :key="index"
                      :src="image"
                      :width="50"
                      :height="50"
                      class="image-item"
                    />
                  </template>
                  <template v-else> 无 </template>
                </div>
              </template>
            </el-table-column>

            <!-- 品名/sku列 -->
            <el-table-column label="品名/sku" align="center">
              <template slot-scope="scope">
                <div>{{ scope.row.productName || "-" }}</div>
                <div>{{ scope.row.productSku || "-" }}</div>
              </template>
            </el-table-column>

            <el-table-column label="GTIN" align="center" min-width="120">
              <template slot-scope="childScope">
                <div v-if="childScope.row.gtins && childScope.row.gtins.length">
                  <div
                    v-for="(gtin, index) in childScope.row.gtins"
                    :key="index"
                  >
                    {{ gtin }}
                  </div>
                </div>
                <div v-else>-</div>
              </template>
            </el-table-column>

            <!-- 入库量 -->
            <el-table-column
              label="入库量"
              align="center"
              prop="actualQuantity"
            />

            <!-- 良品量 -->
            <el-table-column
              label="良品量"
              align="center"
              prop="goodQuantity"
            />

            <!-- 次品量 -->
            <el-table-column
              label="次品量"
              align="center"
              prop="defectiveQuantity"
            />

            <!-- 待检量 -->
            <!-- <el-table-column label="待检量" align="center" prop="waitingQuantity" /> -->

            <!-- 单价 -->
            <el-table-column label="单价" align="center">
              <template slot-scope="scope">
                {{ scope.row.price != null ? scope.row.price : "-" }}
              </template>
            </el-table-column>

            <!-- 单位费用 -->
            <!-- <el-table-column label="单位费用" align="center" prop="unitCost">
              <template slot-scope="scope">
                {{ scope.row.unitCost !== null ? scope.row.unitCost : '-' }}
              </template>
            </el-table-column> -->

            <!-- 单位入库成本 -->
            <el-table-column label="单位入库成本" align="center">
              <template slot-scope="scope">
                {{
                  scope.row.singleProductCost != null
                    ? scope.row.singleProductCost.toFixed(3)
                    : "-"
                }}
              </template>
            </el-table-column>
            <!-- 货值 -->
            <el-table-column label="货值" align="center">
              <template slot-scope="scope">
                <span
                  v-if="
                    scope.row.price != null && scope.row.actualQuantity != null
                  "
                >
                  {{ (scope.row.price * scope.row.actualQuantity).toFixed(2) }}
                </span>
                <span v-else>-</span>
              </template>
            </el-table-column>

            <!-- 费用 -->
            <!-- <el-table-column label="费用" align="center" prop="expense">
              <template slot-scope="scope">
                {{ scope.row.expense !== null ? scope.row.expense : '-' }}
              </template>
            </el-table-column> -->

            <!-- 入库成本 -->
            <el-table-column label="入库成本" align="center">
              <template slot-scope="scope">
                <span
                  v-if="
                    scope.row.singleProductCost != null &&
                    scope.row.actualQuantity != null
                  "
                >
                  {{
                    (
                      scope.row.singleProductCost.toFixed(3) *
                      scope.row.actualQuantity
                    ).toFixed(2)
                  }}
                </span>
                <span v-else>-</span>
              </template>
            </el-table-column>

            <!-- 备注 -->
            <el-table-column label="备注" align="center" prop="remark">
              <template slot-scope="scope">
                {{ scope.row.remark || "-" }}
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>

      <!-- 主表格列 -->
      <el-table-column
        label="入库单号/批次号"
        align="center"
        prop="storageNumber"
      />
      <el-table-column label="采购订单号" align="center" prop="ordersNumber" />
      <!-- <el-table-column label="采购订单下单人" align="center">
        <template slot-scope="scope">
          {{ scope.row.approver }}<br />{{ parseTime(scope.row.approvedTime, "{y}-{m}-{d} {hh}:{ii}:{ss}") }}
        </template>
      </el-table-column> -->
      <el-table-column label="入库仓库" align="center" prop="warehouseName" />
      <el-table-column label="入库类型" align="center" prop="storageType">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.storage_type"
            :value="scope.row.storageType"
          />
        </template>
      </el-table-column>
      <el-table-column label="入库量" align="center" prop="inboundNumber" />
      <el-table-column
        label="总良品量"
        align="center"
        prop="totalPassQuantity"
      />
      <el-table-column
        label="总次品量"
        align="center"
        prop="totalDefectiveQuantity"
      />

      <!-- <el-table-column label="入库状态" align="center" prop="inboundStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.inbound_status" :value="scope.row.inboundStatus" />
        </template>
      </el-table-column> -->
      <el-table-column label="备注" align="center">
        <template slot-scope="scope">
          {{ scope.row.storage_remark ? scope.row.storage_remark : "-" }}
        </template>
      </el-table-column>
      <el-table-column label="入库人/入库时间" align="center">
        <template slot-scope="scope">
          <div>{{ scope.row.depositor ? scope.row.depositor : "-" }}</div>
          <div>
            {{
              scope.row.inboundTime
                ? parseTime(scope.row.inboundTime, "{y}-{m}-{d} {hh}:{ii}:{ss}")
                : "-"
            }}
          </div>
        </template>
      </el-table-column>
      <!-- <el-table-column label="创建人/创建时间" align="center">
        <template slot-scope="scope">
          <div>{{ scope.row.depositor ? scope.row.depositor : '-' }}</div>
          <div>
            {{ scope.row.addTime ? parseTime(scope.row.addTime, "{y}-{m}-{d} {hh}:{ii}:{ss}") : '-' }}
          </div>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="供应商" align="center">
        <template slot-scope="scope">
          {{ scope.row.vendorNumber }}<br />{{ scope.row.accountHolder }}
        </template>
      </el-table-column>
      <el-table-column label="入库人" align="center">
        <template slot-scope="scope">
          {{ scope.row.depositor }}<br />{{ parseTime(scope.row.inboundTime, "{y}-{m}-{d} {hh}:{ii}:{ss}") }}
        </template>
      </el-table-column>
      <el-table-column label="入库数量" align="center" prop="inboundNumber" /> -->

      <!-- 操作列 -->
      <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleDetail(scope.row)"
            v-hasPermi="['depot:ProcuredStorage:detail']">
            详情
          </el-button>

          <el-dropdown @command="handleOperationCommand(scope.row)" trigger="click">
            <el-button size="mini" type="text">
              操作 <i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="submitStorage">提交入库</el-dropdown-item>

            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column> -->
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改采购入库单对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1200px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="入库单号" prop="storageNumber">
          <el-input v-model="form.storageNumber" placeholder="请输入入库单号" />
        </el-form-item>
        <el-form-item
          label="关联采购订单id(tb_procured_orders)"
          prop="ordersId"
        >
          <el-input
            v-model="form.ordersId"
            placeholder="请输入关联采购订单id(tb_procured_orders)"
          />
        </el-form-item>
        <el-form-item label="入库人" prop="depositor">
          <el-input v-model="form.depositor" placeholder="请输入入库人" />
        </el-form-item>
        <el-form-item label="入库时间" prop="inboundTime">
          <el-date-picker
            clearable
            v-model="form.inboundTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择入库时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="入库数量" prop="inboundNumber">
          <el-input v-model="form.inboundNumber" placeholder="请输入入库数量" />
        </el-form-item>
        <el-form-item label="入库状态" prop="inboundStatus">
          <el-radio-group v-model="form.inboundStatus">
            <el-radio
              v-for="dict in dict.type.inbound_status"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-divider content-position="center">入库产品信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAddInboundProducts"
              >添加</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="handleDeleteInboundProducts"
              >删除</el-button
            >
          </el-col>
        </el-row>
        <el-table
          :data="inboundProductsList"
          :row-class-name="rowInboundProductsIndex"
          @selection-change="handleInboundProductsSelectionChange"
          ref="inboundProducts"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            label="序号"
            align="center"
            prop="index"
            width="50"
          />
          <el-table-column
            label="关联产品表(tb_product)"
            prop="productId"
            width="150"
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.productId"
                placeholder="请输入关联产品表(tb_product)"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="产品入库数量(良品)"
            prop="tertullianProductsNumber"
            width="150"
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.tertullianProductsNumber"
                placeholder="请输入产品入库数量(良品)"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="产品入库数量(次品)"
            prop="subProductsNumber"
            width="150"
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.subProductsNumber"
                placeholder="请输入产品入库数量(次品)"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="产品入库金额(良品)"
            prop="tertullianProductsAmount"
            width="150"
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.tertullianProductsAmount"
                placeholder="请输入产品入库金额(良品)"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="产品入库金额(次品)"
            prop="subProductsAmount"
            width="150"
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.subProductsAmount"
                placeholder="请输入产品入库金额(次品)"
              />
            </template>
          </el-table-column>
          <el-table-column label="产品总金额" prop="productsAmount" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.productsAmount"
                placeholder="请输入产品总金额"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listProcuredStorage,
  getProcuredStorage,
  delProcuredStorage,
  addProcuredStorage,
  updateProcuredStorage,
} from "@/api/depot/ProcuredStorage";
import { getSelectPreWarehouseTreeList } from "@/api/procured/plan";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "ProcuredStorage",
  dicts: ["inbound_status", "storage_type"],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedInboundProducts: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购入库单表格数据
      ProcuredStorageList: [],
      // 入库产品表格数据
      inboundProductsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        storageNumber: null,
        ordersNumber: null,
        ordersId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 仓库列表
      warehouseOptions: [],
    };
  },
  created() {
    this.getList();
    this.getPreWarehouse();
  },
  methods: {
    /** 查询采购入库单列表 */
    getList() {
      this.loading = true;
      listProcuredStorage(this.queryParams).then((response) => {
        this.ProcuredStorageList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        storageId: null,
        storageNumber: null,
        ordersId: null,
        depositor: null,
        inboundTime: null,
        inboundNumber: null,
        inboundStatus: null,
        deleteStatus: null,
        addTime: null,
        updateTime: null,
      };
      this.inboundProductsList = [];
      this.resetForm("form");
    },
    /** 查询仓库 */
    getPreWarehouse() {
      getSelectPreWarehouseTreeList().then((response) => {
        this.warehouseOptions = response.data;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.storageId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加采购入库单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const storageId = row.storageId || this.ids;
      getProcuredStorage(storageId).then((response) => {
        this.form = response.data;
        this.inboundProductsList = response.data.inboundProductsList;
        this.open = true;
        this.title = "修改采购入库单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.inboundProductsList = this.inboundProductsList;
          if (this.form.storageId != null) {
            updateProcuredStorage(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProcuredStorage(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const storageIds = row.storageId || this.ids;
      this.$modal
        .confirm('是否确认删除采购入库单编号为"' + storageIds + '"的数据项？')
        .then(function () {
          return delProcuredStorage(storageIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 入库产品序号 */
    rowInboundProductsIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 入库产品添加按钮操作 */
    handleAddInboundProducts() {
      let obj = {};
      obj.productId = "";
      obj.tertullianProductsNumber = "";
      obj.subProductsNumber = "";
      obj.tertullianProductsAmount = "";
      obj.subProductsAmount = "";
      obj.productsAmount = "";
      this.inboundProductsList.push(obj);
    },
    /** 入库产品删除按钮操作 */
    handleDeleteInboundProducts() {
      if (this.checkedInboundProducts.length == 0) {
        this.$modal.msgError("请先选择要删除的入库产品数据");
      } else {
        const inboundProductsList = this.inboundProductsList;
        const checkedInboundProducts = this.checkedInboundProducts;
        this.inboundProductsList = inboundProductsList.filter(function (item) {
          return checkedInboundProducts.indexOf(item.index) == -1;
        });
      }
    },
    /** 复选框选中数据 */
    handleInboundProductsSelectionChange(selection) {
      this.checkedInboundProducts = selection.map((item) => item.index);
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "depot/ProcuredStorage/export",
        {
          ...this.queryParams,
        },
        `ProcuredStorage_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
